<template>
  <section>
    <el-dialog
      :title="user.id == 0 ? '添加用户' : '编辑用户' "
      :visible.sync="visible"
      :value="value"
      @close="close"
      width="500px"
    >
      <el-form
        :model="user"
        :rules="rules"
        ref="userForm"
      >
        <el-form-item
          label="姓名"
          :label-width="labelWidth"
          prop="realName"
        >
          <el-input
            v-model="user.realName"
            auto-complete="off"
            maxlength="32"
            suffix-icon="fa fa-vcard"
            placeholder="请填写用户姓名"
          />
        </el-form-item>
        <el-form-item
          label="手机号码"
          :label-width="labelWidth"
          prop="mobile"
        >
          <el-input
            v-model="user.mobile"
            auto-complete="off"
            maxlength="11"
            suffix-icon="fa fa-mobile"
            placeholder="请填写用户手机号码"
          />
        </el-form-item>
        <el-form-item
          label="性别"
          :label-width="labelWidth"
          prop="sex"
        >
          <el-select
            v-model="user.sex"
            placeholder="请选择性别"
          >
            <el-option
              v-for="item in sexes"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="small"
          @click="cancle('userForm')"
        >取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="submit('userForm')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<style>
</style>
<script>
    import {mapState} from "vuex";

    export default {
        name: "AddAndEdit",
        data() {
            var validateMobile = (rule, value, callback) => {
                var reg = /^(13[0-9]|14[5|6|7|9]|15[0|1|2|3|5|6|7|8|9]|16[5|6]|17[0|1|2|3|4|5|6|7|8]|18[0|1|2|3|5|6|7|8|9]|19[1|8|9])\d{8}$/;
                if (value === "") {
                    callback(new Error("请输入手机号码"));
                } else {
                    if (reg.test(this.user.mobile)) {
                        callback();
                    } else {
                        callback(new Error("请输入正确的手机号码"));
                    }
                }
            };
            return {
                organizations: [],
                defaultProps: {
                    children: "sub",
                    value: "id",
                    label: "name"
                },
                props: {
                    value: "value",
                    label: "name",
                    children: "child"
                },
                visible: false,
                labelWidth: "",
                accountTypes: [],
                areas: [],
                user: {
                    id: 0,
                    realName: "",
                    mobile: "",
                    sex: ''
                },
                sexes: [],
                rules: {
                    realName: [{required: true, message: "请输入姓名", trigger: "blur"}],
                    mobile: [
                        {required: true, validator: validateMobile, trigger: "blur"}
                    ]
                }
            };
        },
        watch: {
            value: {
                deep: true,
                immediate: true,
                handler: function (val) {
                    this.visible = val.show;
                    this.labelWidth = val.formLabelWidth || "120px";
                    this.user = val.user;
                    this.loadData();
                }
            },
            visible(val) {
                if (!val) this.$emit("on-show-change", this.$data);
            },
            user: {
                handler() {
                    if (this.user.organizationIds && this.user.organizationIds.length) {
                        this.user.orgId = this.user.organizationIds[
                        this.user.organizationIds.length - 1
                            ];
                    }
                },
                immediate: true,
                deep: true
            }
        },
        created() {
            // this.$api.organization.tree(0, false, result => {
            //   this.organizations = result.tree || [];
            // });
        },
        computed: {
            ...mapState({
                codebooks: state => state.codebooks.codebooks
            })
        },
        mounted() {
            this.sexes = this.codebooks ? this.codebooks.sexs : [];
        },
        methods: {
          close() {
            this.cancle('userForm');
          },
          cancle(formName) {
                this.$refs[formName].clearValidate();
                this.visible = false;
                this.user = {
                    id: 0
                };
            },
            loadData() {
                if (!this.user || !this.user.id || this.user.id <= 0) {
                    return;
                }
                this.$api.user.detail(this.user.id, result => {
                    this.user = result.user;
                    this.user.sex = this.user.sex ? this.user.sex.value : '';
                });
            },

            submit(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        const callback = () => {
                            this.cancle(formName);
                        };
                        if (this.user.mobile) {
                            //如果填了手机号，则校验手机
                            var reg = /^(13[0-9]|14[5|6|7|9]|15[0|1|2|3|5|6|7|8|9]|16[5|6]|17[0|1|2|3|4|5|6|7|8]|18[0|1|2|3|5|6|7|8|9]|19[1|8|9])\d{8}$/;
                            if (!reg.test(this.user.mobile)) {
                                this.$message({
                                    type: "error",
                                    message: "手机号格式错误"
                                });
                                return;
                            }
                        }
                        this.user.id
                            ? this.$api.user.update(this.user, callback)
                            : this.$api.user.save(this.user, callback);
                    } else {
                        return false;
                    }
                });
            }
        },
        props: {
            value: {
                type: Object,
                default: function () {
                    return {
                        show: false,
                        formLabelWidth: "120px",
                        user: {
                            id: 0,
                            types: []
                        }
                    };
                }
            }
        }
    };
</script>
